﻿using MeetingAssistant.Component.Data.Enum;
using MeetingAssistant.Component.Tools;
using MeetingAssistant.Component.Tools.helpers;
using MeetingAssistant.CoreBLL.Service.Member.Interface;
using MeetingAssistant.Domain.Model.Member;
using MeetingAssistant.ViewModel;
using MeetingAssistant.ViewModel.Member;
using MeetingAssistant.Web.Extension.Common;
using MeetingAssistant.Web.Extension.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web;
using LinqToExcel;
using Remotion.Data.Linq;
using MeetingAssistant.Extension.Common;
using System.Text;
using System.Data.Entity.Validation;

namespace MeetingAssistant.Areas.Member.Controllers
{
    public class UserController : Controller
    {
        private readonly IUserService _userService;
        private readonly IRoleService _roleService;
        private readonly IUserGroupService _userGroupService;
        


        public UserController(IUserGroupService userGroupService, IUserService userService, IRoleService roleService)
        {
            this._roleService = roleService;
            this._userGroupService = userGroupService;
            this._userService = userService;
        }

        
        // GET: Member/User
        [Layout]
        public ActionResult Index()
        {
            GetButtonPermissions();
            var enabledItems = DataSourceHelper.GetIsTrue();
            ViewBag.EnableItems = enabledItems;
            return View();
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <param name="userName"></param>
        /// <param name="enable"></param>
        /// <returns></returns>
        public JsonResult GetUsers(int limit, int offset, string userName, int enable)
        {
            int total = 0;
            Expression<Func<User, bool>> wh = c => true;
            if (!string.IsNullOrEmpty(userName))
            {
                wh = wh.And(c => c.TrueName.Contains(userName.Trim()));
            }
            if (enable >= 0)
            {
                var yesOrNot = enable != 0;
                wh = wh.And(c => c.Enabled == yesOrNot);
            }
            HttpCookie loginCookie = Request.Cookies["loginCookie"];
            var name = loginCookie.Values["companyName"];
            var result = _userService.GetListUserVM(wh, limit, offset, out total, name);
            return Json(new { total = total, rows = result }, JsonRequestBehavior.AllowGet);
        }

       //public string GetCookie()
       // {
       //     HttpCookie loginCookie = Request.Cookies["loginCookie"];
       //     var companyId = loginCookie.Values["companyId"];
       //     return companyId;
       // }

        public ActionResult Create()
        {
            var model = new UserVM();
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Create(UserVM userVM)
        {
            //移除Model中不需要验证的属性password
            ValidationHelper.RemoveValidationError(ModelState, "Password");
            if (!ModelState.IsValid)
                return Json(new OperationResult(OperationResultType.ParamError,"参数错误，请重新输入！"));
            userVM.Password = EncryptionHelper.GetMd5Hash("123456");
            HttpCookie loginCookie = Request.Cookies["loginCookie"];
            var companyId = loginCookie.Values["companyId"];
            var result = _userService.Insert(userVM, Convert.ToInt32(companyId));
            result.Message = result.Message ?? result.ResultType.GetDescription();
            return Json(result);
        }

        #region 修改
        /// <summary>
        /// 打开修改框
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [IsAjax]
        public ActionResult Edit(int id = 0)
        {
            var user = _userService.Users.FirstOrDefault(c => c.Id == id);
            if (user == null)
                return PartialView("Create", new UserVM());
            var model = new UserVM()
            {
                Id = user.Id,
                UserName = user.UserName,
                TrueName = user.TrueName,
                Sex = user.Sex,
                IdentityNumber = user.IdentityNumber,
                Email = user.Email,
                Phone = user.Phone,
                Address = user.Address,
                Department = user.Department,
                Enabled = user.Enabled,
            };
            return PartialView("Create", model);
        }

        [HttpPost]
        public ActionResult Edit(UserVM userVM)
        {
            ValidationHelper.RemoveValidationError(ModelState, "Password");
            if (!ModelState.IsValid)
                return Json(new OperationResult(OperationResultType.ParamError, "参数错误，请重新输入！"));
            var result = _userService.Update(userVM);
            result.Message = result.Message ?? result.ResultType.GetDescription();
            return Json(result);
        }
        #endregion


        [HttpPost]
        public ActionResult Delete()
        {
            var userlist = Request.Form["arrselections"];
            IEnumerable<UserVM> list = JsonConvert.DeserializeObject<List<UserVM>>(userlist);
            var result = _userService.Delete(list);
            result.Message = result.Message ?? result.ResultType.GetDescription();
            return Json(result);
        }

        [HttpPost]
        public ActionResult ResetPassword()
        {
            var userlist = Request.Form["arrselections"];
            IEnumerable<UserVM> list = JsonConvert.DeserializeObject<List<UserVM>>(userlist);
            var result = _userService.ResetPassword(list);
            result.Message = result.Message ?? result.ResultType.GetDescription();
            return Json(result);
        }

        #region 设置角色
        public ActionResult SetRoles(int id = 0)
        {
            ViewBag.KeyId = id;
            var user = _userService.Users.Include(c => c.Roles).FirstOrDefault(c => c.Id == id);
            if(user == null)
            {
                return PartialView("Create", new UserVM()); 
            }
            else
            {
                List<int> ids = user.Roles.Select(c => c.Id).ToList();
                var list = _roleService.Roles.Where(c => c.Enabled == true).Select(c => new CheckBoxVM()
                {
                    Name = "chkRoles",
                    Value = c.Id,
                    Discription = c.RoleName,
                    IsChecked = ids.Contains(c.Id)
                }).ToList();
                return PartialView("_SetCheckBox", list);

            }
        }
        [HttpPost]
        public ActionResult SetRoles(int keyId, string[] chkRoles)
        {
            if(keyId <= 0)
            {
                return Json(new OperationResult(OperationResultType.ParamError, "参数错误，请重新输入！"));
            }
            OperationResult result = _userService.UpdateUserRoles(keyId, chkRoles);
            result.Message = result.Message ?? result.ResultType.GetDescription();
            return Json(result);
        }
        #endregion

        #region 设置用户组
        // GET: /Member/User/SetUserGroups
        [IsAjax]
        public ActionResult SetUserGroups(int id = 0)
        {
            ViewBag.KeyId = id;
            var user = _userService.Users.Include(c => c.UserGroups).FirstOrDefault(c => c.Id == id);
            if (user == null)
            {
                return PartialView("Create", new UserVM());
            }
            else
            {
                List<int> ids = user.UserGroups.Select(c => c.Id).ToList();
                var list = _userGroupService.UserGroups.Where(c => c.Enabled == true).Select(c => new CheckBoxVM()
                {
                    Name = "chkUserGroups",
                    Value = c.Id,
                    Discription = c.GroupName,
                    IsChecked = ids.Contains(c.Id)

                }).ToList();
                return PartialView("_SetCheckBox", list);
            }
        }
        [HttpPost]
        public ActionResult SetUserGroups(int keyId, string[] chkUserGroups)
        {
            if (keyId <= 0)
            {
                return Json(new OperationResult(OperationResultType.ParamError, "参数错误!"));
            }
            OperationResult result = _userService.UpdateUserGroups(keyId, chkUserGroups);
            result.Message = result.Message ?? result.ResultType.GetDescription();
            return Json(result);
        }
        #endregion

        #region 用户信息导入
        public ActionResult Upload()
        { 
            return PartialView();
        }
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            var fileName = Request.Form["name"]; 
            string fileRelName = fileName.Substring(0, fileName.LastIndexOf('.'));
            int index = Convert.ToInt32(Request.Form["chunk"]);
            var guid = Request.Form["guid"];
            var dir = Server.MapPath("~/Upload");
            dir = Path.Combine(dir, fileRelName);
            if (!System.IO.Directory.Exists(dir))
                System.IO.Directory.CreateDirectory(dir);
            string filePath = Path.Combine(dir, index.ToString());
            var data = Request.Files["file"];
            data.SaveAs(filePath);
            return Json(new { erron = 0 });
        }
        public ActionResult Merge()
        {
            var guid = Request.Form["guid"];
            var uploadDir = Server.MapPath("~/Upload");
            var fileName = Request.Form["fileName"];
            string fileRelName = fileName.Substring(0, fileName.LastIndexOf('.'));
            var dir = Path.Combine(uploadDir, fileRelName);
            var files = System.IO.Directory.GetFiles(dir);
            var finalPath = Path.Combine(uploadDir, fileName);
            var fs = new FileStream(finalPath, FileMode.Create);
            foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))
            {
                var bytes = System.IO.File.ReadAllBytes(part);
                fs.Write(bytes, 0, bytes.Length);
                bytes = null;
                System.IO.File.Delete(part);//删除分块
            }
            fs.Flush();
            fs.Close();
            System.IO.Directory.Delete(dir);//删除文件夹
            
            try
            {
                var excel = new ExcelQueryFactory(finalPath);
                var workSheetNames = excel.GetWorksheetNames();
                
                var userList = new List<UserVM>();

                foreach (var item in workSheetNames)
                {
                //    if (item.Contains("用户表"))
                //    {
                        //var columnNames = excel.GetColumnNames(0);
                        excel.AddMapping<UserVM>(d => d.Id, "序号");
                        excel.AddMapping<UserVM>(d => d.UserName, "用户名");
                        excel.AddMapping<UserVM>(d => d.Password, "密码");
                        excel.AddMapping<UserVM>(d => d.TrueName, "姓名");
                        excel.AddTransformation<UserVM>(d => d.Sex, d => (d == "男") ? true : false);
                        excel.AddMapping<UserVM>(d => d.IdentityNumber, "身份证号");
                        excel.AddMapping<UserVM>(d => d.Email, "邮箱");
                        excel.AddMapping<UserVM>(d => d.Phone, "电话");
                        excel.AddMapping<UserVM>(d => d.Address, "个人住址");
                        excel.AddMapping<UserVM>(d => d.Department, "所属部门");

                        List<UserVM> list = (from user in excel.Worksheet<UserVM>(item)
                                             select user).ToList();
                        HttpCookie loginCookie2 = Request.Cookies["loginCookie"];
                        var companyId = loginCookie2.Values["companyId"];
                        var index = 1;
                        if(list.Count() == 0) return Json(new OperationResult(OperationResultType.Error, "请检查Excel格式是否正确！"));
                        foreach (var user in list)
                        {
                            if (index == list.Count()) break;
                            var result = _userService.Insert(user, Convert.ToInt32(companyId));
                            index += 1;
                        }
                //    }
                }
                return Json(new OperationResult(OperationResultType.Success, "导入成功！"));
            }
            catch(Exception ex)
            {
                throw new Exception(ex.Message);
                return Json(new OperationResult(OperationResultType.ParamError, "请检查Excel格式是否正确！"));
            }
        }
        #endregion

        #region 私有函数 获取按钮可见权限
        [NonAction]
        private void GetButtonPermissions()
        {
            string userId = ((System.Web.Security.FormsIdentity)(HttpContext.User.Identity)).Ticket.UserData;
            List<Permission> permissionCache =
                (List<Permission>)CacheHelper.GetCache(CacheKey.StrPermissionsByUid + "_" + userId);
            //新增按钮
            Permission addUserButton =
                permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.AddUser.ToString());
            ViewBag.AddUserButton = addUserButton;
            //修改按钮
            Permission updateUserButton =
                permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.UpdateUser.ToString());
            ViewBag.UpdateUserButton = updateUserButton;
            //删除按钮
            Permission deleteUserButton =
                permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.DeleteUser.ToString());
            ViewBag.DeleteUserButton = deleteUserButton;
            //重置密码按钮
            Permission resetPwdUserButton =
                permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.ResetPwdUser.ToString());
            ViewBag.ResetPwdUserButton = resetPwdUserButton;
            //设置用户组
            Permission setGroupUserButton =
           permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.SetGroupUser.ToString());
            ViewBag.SetGroupUserButton = setGroupUserButton;
            //设置角色
            Permission setRolesUserButton =
           permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.SetRolesUser.ToString());
            ViewBag.SetRolesUserButton = setRolesUserButton;
            //用户信息导入
            Permission uploadUserButton =
                permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.UploadUser.ToString());
            ViewBag.UploadUserButton = uploadUserButton;
        }
        #endregion
    }
}